package com.mgl.movesprite.game.model;

import org.andengine.entity.scene.Scene;
import org.andengine.entity.sprite.Sprite;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.opengl.vbo.VertexBufferObjectManager;

import com.mgl.movesprite.EntitySpriteLevelBase;
import com.mgl.movesprite.game.factory.GameObjectFactory;
import com.mgl.util.Point;

public class Shot extends EntitySpriteLevelBase {

	private Sprite target = null;
	private float speed = 50;
	private boolean hit = false;
	private float explodeTime = 0;

	public Shot(float pX, float pY, ITextureRegion pTextureRegion,
			VertexBufferObjectManager pVertexBufferObjectManager,
			GameObjectFactory gameObjectFactory) {
		super(pX, pY, pTextureRegion, pVertexBufferObjectManager,
				gameObjectFactory);
		hit = false;
	}

	@Override
	public void update(float pSecondsElapsed, Level level) {
		// TODO Auto-generated method stub
		
	}
	
	public void update(float pSecondsElapsed, Scene scene) {
		try {
			if (target == null) {
				scene.detachChild(this);
				hit = false;
			}
			if (hit) {
				hitTarget(pSecondsElapsed, scene);
			} else {
				moveToTarget(pSecondsElapsed);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private void hitTarget(float pSecondsElapsed, Scene scene) {

		explodeTime += pSecondsElapsed;
		if (explodeTime > 2) {
			scene.detachChild(this);
			hit = false;
			explodeTime = 0;
			target = null;
		}

	}

	private void moveToTarget(float pSecondsElapsed) {

		float x = this.getX();
		float y = this.getY();

		Point currentPoint = new Point(x, y);
		Point pointToMove = new Point(target.getX(), target.getY());

		float distance = pSecondsElapsed * speed;

		float disAux = Point.distanceBetween(currentPoint, pointToMove);

		if (distance > disAux) {

			this.setPosition(pointToMove.getX(), pointToMove.getY());
			hit = true;
		}

		float angle = Point.angleBetween(currentPoint, pointToMove);

		float dx = distance * (float) Math.cos(angle);
		float dy = distance * (float) Math.sin(angle);

		this.setPosition(x + dx, y + dy);

	}

	public Sprite getTarget() {
		return target;
	}

	public void setTarget(Sprite target) {
		this.target = target;
	}

	public float getSpeed() {
		return speed;
	}

	public void setSpeed(float speed) {
		this.speed = speed;
	}

	public boolean isHit() {
		return hit;
	}

	public void setHit(boolean hit) {
		this.hit = hit;
	}

	public float getExplodeTime() {
		return explodeTime;
	}

	public void setExplodeTime(float explodeTime) {
		this.explodeTime = explodeTime;
	}

	

}
